package com.common.utils.utils;

import com.common.domain.MyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @program: anqi-shengting-backend
 * @description: 安企工具类
 * @author: zhaoym
 * @create: 2022-08-25 16:21
 */
public class AnqiUtil {

    /**
     * 对象转map
     *
     * @param bean 实体类
     * @return
     */
    public static Map<String, Object> tranceClassToMap(Object bean) {
        if (bean == null) {
            return Collections.emptyMap();
        }
        Map<String, Object> map = new HashMap<>();
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if (String.class.isAssignableFrom(field.getType()) && StringUtils.isNotEmpty(String.valueOf(field.get(bean)))) {
                    map.put(field.getName(), field.get(bean));
                } else if (!String.class.isAssignableFrom(field.getType()) && field.get(bean) != null) {
                    map.put(field.getName(), field.get(bean));
                }
            }catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new MyException("数据转换错误："+e.getMessage());
            }

        }
        return map;
    }


    public static <T> List<T> copyList(List source, Class<T> clazz) {
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)){
            if (!CollectionUtils.isEmpty(source)){
                for (Object c: source) {
                    T obj = copy(c, clazz);
                    target.add(obj);
                }
            }
        }
        return target;
    }

    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(source, obj);
        return obj;
    }
}
